package com.kedacom.ctsp.authz.security.provider;

import com.kedacom.ctsp.authz.AuthenticationService;
import com.kedacom.ctsp.authz.token.TokenRegistry;
import org.springframework.context.ApplicationListener;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author sunchenjie
 * @date 2017/12/8
 */
public interface AuthzSessionRegistry extends SessionRegistry,
        ApplicationListener<SessionDestroyedEvent>, TokenRegistry {

    /**
     * 自定义登录
     *
     * @param authenticationService
     * @param request
     * @param token
     * @param username
     */
    default void signIn(AuthenticationService authenticationService, HttpServletRequest request, String token, String username) {
        AuthUserDetails principal = new AuthUserDetails(authenticationService.loadUserByUsername(username));

        PreAuthenticatedAuthenticationToken auth =
                new PreAuthenticatedAuthenticationToken(principal, token, principal.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(auth);

        HttpSession session = request.getSession(true);
        session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());

        registerNewSession(token, principal);
        SecurityContextHolder.getContext().setAuthentication(auth);
    }


}
